import os
import time

from apps.contents.models import ContentCategory
from meiduo_project import settings
from utils.goods import get_categories


def generate_static_index_html():
    # 1查询相关数据
    # 获取频道和分类数据
    categories = get_categories()

    # 广告数据
    contents = {}
    # 所有广告分类
    content_categories = ContentCategory.objects.all()
    # 遍历 获取分类下所有广告 添加到字典
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板的上下文
    context = {
        'categories': categories,
        'contents': contents,
    }

    # 2加载需要渲染模板
    from django.template import loader
    # 获取模板对象
    index_template = loader.get_template('index.html')

    # 3把数据渲染到模板上
    index_html_data = index_template.render(context)

    # 4把渲染好的模板保存成html文件，写入到指定文件
    # settings.BASE_DIR         /home/halon/Desktop/meiduo_pro/meiduo
    # os.path.dirname(settings.BASE_DIR)      /home/halon/Desktop/meiduo_pro

    # / home / halon / Desktop / meiduo_pro/front_end_pc/index.html

    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/index.html')
    print("生成主页index", time.ctime())

    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(index_html_data)
